package com.example.demo.controller;

import com.example.demo.utils.Base64;
import com.example.demo.utils.PassToken;
import com.example.demo.utils.ResponseResult;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Base64Utils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class CodeController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @PassToken
    @GetMapping("/getCheckCode")
    public ResponseResult getCheckCode(HttpServletResponse response){
        // 保存验证码信息
        String uuid = UUID.randomUUID()+"";
        String verifyKey = "captcha_codes:"+ uuid;
        String capStr = null, code = null;
        BufferedImage image = null;

        capStr = code = captchaProducer.createText();//45EE
        image = captchaProducer.createImage(capStr);//创建验证码图片

        redisTemplate.opsForValue().set(verifyKey, code, 2, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return ResponseResult.createByFail(500,"获取验证码失败");
        }

         Map<String,Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return ResponseResult.createBySuccess(200,map,"获取成功");
    }
}
